# import sys
# sys.path.append('/home/class2021/.local/lib/python3.6/site-packages')
import os
import json
from time import sleep
import requests
from utils.core import CoreCaller
from utils import readDBinfo, TaskScheduler, log


def Initialize():
    # 从conf.ini读取数据库信息
    remote_db_config = readDBinfo(os.path.dirname(__file__)+'/conf.ini')

    # 构建CoreCaller对象
    global core_caller
    core_caller = CoreCaller(remote_db_config)

    # 构建任务调度器
    global ts
    ts = TaskScheduler(background=True)


def update_News():
    log.logger.info("update_DBCategory started...")
    core_caller.update_DBCategory()
    log.logger.info("update_DBCategory ended...")

    log.logger.info("tag_DBNews started...")
    core_caller.tag_DBNews()
    log.logger.info("tag_DBNews ended...")


def update_Hotwords():
    log.logger.info("update_Hotwords started...")
    core_caller.update_Hotwords()
    log.logger.info("update_Hotwords ended...")


def update_sentiment():
    # 情感分析性能：1000条数据，10分钟
    log.logger.info("senti_DBNews started...")
    core_caller.senti_DBNews()
    log.logger.info("senti_DBNews ended...")


def update_Cluster():
    log.logger.info("update_DBCluster started...")
    core_caller.update_DBCluster()
    log.logger.info("update_DBCluster ended...")


def revive_job(url):
    '''查询业务组是否要求重启某服务，并重启'''

    try:
        revive_msg = requests.get(url, timeout=5)
    except requests.exceptions.ConnectionError as e:
        log.logger.error(e)
        ts.stop()
        exit()

    if revive_msg.status_code == 404:
        log.logger.error("404 Page Not Found, EXIT...")
        ts.stop()
        exit()

    revive_job = revive_msg.content

    if revive_job == "None":
        return False

    flag = False
    if revive_job == "update_Hotwords_task":
        flag = ts.new_job(update_Hotwords, hours=1, id=revive_job)
    elif revive_job == "update_News_task":
        flag = ts.new_job(update_News, hours=1, id=revive_job)
    elif revive_job == "update_Sentiment_task":
        flag = ts.new_job(update_sentiment, hours=1, id=revive_job)
    elif revive_job == "update_Cluster_task":
        flag = ts.new_job(update_Cluster, hours=1, id=revive_job)

    api_url = "http://localhost:10520/api/heart/al_activated"
    data = {'process': revive_job, 'status': flag}
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    requests.post(api_url, data=json.dumps(data), timeout=10, headers=headers)
    return True


def send_heartbeats():
    api_url = "http://localhost:10520/api/heart/al_getactive"
    data = {'task_alive': [task.id for task in ts.get_jobs()]}
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    requests.post(api_url, data=json.dumps(data), timeout=10, headers=headers)


if __name__ == "__main__":
    Initialize()

    ts.new_job(send_heartbeats, minutes=30, id="heartbeats_task")
    ts.new_job(update_News, hours=1, id="update_News_task")
    ts.new_job(update_sentiment, hours=1, id="update_Sentiment_task")
    ts.new_job(update_Hotwords, hours=1, id="update_Hotwords_task")
    ts.new_job(update_Cluster, hours=1, id="update_Cluster_task")
    ts.run()

    while 1:
        revive_job("http://localhost:10520/api/heart/al_activate")
        sleep(10)
